<?php

namespace app\admin\controller;

use app\model\GoodsModel;
use app\model\GoodsKuModel;
use support\Request;
use support\Response;
use Exception;
use app\model\Util;
use app\model\GoodsSpecModel;
use app\model\GoodsImageModel;
use app\model\OrderItemModel;
use support\Log;

class GoodsController
{
    /**
     * 获取商品列表
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        try {
            $current = (int)$request->get('current', 1);
            $pageSize = (int)$request->get('pageSize', 10);
            $title = $request->get('title', '');
            $catId = (int)$request->get('cat_id', 0);
            $subCatId = (int)$request->get('sub_cat_id', 0);
            $secondDay = $request->get('second_day', '');

            $query = GoodsModel::query()
                ->orderBy('sort_by', 'desc')
                ->orderBy('id', 'desc');

            if (!empty($title)) {
                $query->where('title', 'like', '%' . $title . '%');
            }
            
            // 分类筛选
            if ($catId > 0) {
                $query->where('cat_id', $catId);
            }
            
            // 子分类筛选
            if ($subCatId > 0) {
                $query->where('sub_cat_id', $subCatId);
            }

            if (!empty($secondDay)) {
                $query->where('second_day', '=',$secondDay);
            }
                
            $total = $query->count();
            $list = $query->offset(($current - 1) * $pageSize)
                ->limit($pageSize)
                ->get();

            foreach ($list as &$item) {
                $item['image_url'] = Util::pathToUrl($item->image);
                $item['created_at'] = date('Y-m-d H:i:s', $item->created_at);
                
                // 获取分类名称
                if (!empty($item->cat_id)) {
                    $catModel = \app\model\GoodsCatModel::find($item->cat_id);
                    $item['cat_name'] = $catModel ? $catModel->name : '';
                }
                
                // 获取子分类名称
                if (!empty($item->sub_cat_id)) {
                    $subCatModel = \app\model\GoodsCatModel::find($item->sub_cat_id);
                    $item['sub_cat_name'] = $subCatModel ? $subCatModel->name : '';
                }
                
                // 统计支付订单数（已支付的订单）
                $orderCount = OrderItemModel::leftJoin('order', 'order_item.order_id', '=', 'order.id')
                    ->where('order_item.goods_id', $item->id)
                    ->where('order.status', 'pay')
                    ->count();
                $item['order_count'] = $orderCount;
                
                // 统计相册图片数
                $imageCount = GoodsImageModel::where('goods_id', $item->id)
                    ->count();
                $item['image_count'] = $imageCount;

                if($item['pre_sale'] == 1){
                    $item['pre_sale_start_at'] = date('Y-m-d', $item->pre_sale_start_at);
                    $item['pre_sale_end_at'] = date('Y-m-d', $item->pre_sale_end_at);
                }else{
                    $item['pre_sale_start_at'] = '';
                    $item['pre_sale_end_at'] = '';
                }

                $item['pre_sale'] =(string)$item['pre_sale'];
            }
                
            return json([
                'data' => [
                    'list' => $list,
                    'total' => $total
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 提交/创建商品
     * @param Request $request
     * @return Response
     */
    public function submit(Request $request): Response
    {
        try {
            $data = $request->post();
            
            if (empty($data['title']) || empty($data['image'])) {
                throw new Exception('商品名称和图片不能为空');
            }

            // 判断是新建还是编辑
            if (!empty($data['id'])) {
                $goods = GoodsModel::find($data['id']);
                if (!$goods) {
                    throw new Exception('商品不存在');
                }
            } else {
                $goods = new GoodsModel();
            }


            // 预售
            if($data['pre_sale'] == 1){
                if(empty($data['pre_sale_start_at']) || empty($data['pre_sale_end_at'])){
                    throw new Exception('预售开始时间和预售结束时间不能为空');
                }

                $data['pre_sale_start_at'] = strtotime($data['pre_sale_start_at']);
                $data['pre_sale_end_at'] = strtotime($data['pre_sale_end_at']);
            }else{
                $data['pre_sale_start_at'] = 0;
                $data['pre_sale_end_at'] = 0;
            }

            if(empty($data['second_day'])){
                $data['second_day'] = null;
            }

            if(empty($data['recommend_day'])){
                $data['recommend_day'] = null;
            }

            $goods->fill($data);
            $goods->updated_at = time();
            
            // 新建时设置创建时间
            if (empty($data['id'])) {
                $goods->created_at = time();
            }
            
            if (!$goods->save()) {
                throw new Exception(empty($data['id']) ? '添加失败' : '更新失败');
            }

            return json([
                'data' => $goods,
                'msg' => empty($data['id']) ? '添加成功' : '更新成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
    * 删除商品
     * @param Request $request
     * @return Response
     */
    public function delete(Request $request): Response
    {
        try {
            $id = $request->post('id');
            
            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $goods = GoodsModel::find($id);
            if (!$goods) {
                throw new Exception('商品不存在');
            }

            if (!$goods->delete()) {
                throw new Exception('删除失败');
            }

            return json([
                'data' => null,
                'msg' => '删除成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 一个商品的规格
     * @param \support\Request $request
     * @return void
     */
    public function specs(Request $request): Response{
        try {
            $goods_id = $request->get('goods_id');
            $goods = GoodsModel::find($goods_id);
            if (!$goods) {
                throw new Exception('商品不存在');
            }
            $specNames = !empty($goods->spec_names) ? $goods->spec_names : '';
            $specNameArr = explode('@', $specNames);

            $specs = [];
            foreach ($specNameArr as $specName) {
                $spec = GoodsSpecModel::where('goods_id', $goods_id)->where('spec_name', $specName)->first();
                if (empty($spec)) {
                    continue;
                }

                $specValues = empty($spec->spec_value) ? [] : explode('@', $spec->spec_value);
                $specValues = array_filter($specValues, function($value) {
                    return !empty($value);
                });

                $specs[] = [
                    'id' => $spec->id,
                    'spec_name' => $spec->spec_name,
                    'spec_values' => $specValues,
                ];
            }

            

            return json([
                'data'=>[
                    'specs' => $specs,
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    public function addSpec(Request $request): Response{
        try {
            $data = $request->post();
            $goods_id = $data['goods_id'];
            $spec_name = $data['spec_name'];

            $goods = GoodsModel::find($goods_id);
            if (!$goods) {
                throw new Exception('商品不存在');
            }

            $specNames = !empty($goods->spec_names) ? $goods->spec_names : '';
            $specNameArr = explode('@', $specNames);

            if (in_array($spec_name, $specNameArr)) {
                throw new Exception('规格名称已存在');
            }

            $specNameArr[] = $spec_name;
            $specNameArr = array_filter($specNameArr, function($value) {
                return !empty($value);
            });
            $specNames = implode('@', $specNameArr);
            $goods->spec_names = $specNames;
            if (!$goods->save()) {
                throw new Exception('添加失败');
            }

            $check = GoodsSpecModel::where('goods_id', $goods_id)->where('spec_name', $spec_name)->first();
            if (empty($check)) {
                $spec = new GoodsSpecModel();
                $spec->goods_id = $goods_id;
                $spec->spec_name = $spec_name;
                $spec->save();
            }

            return json([
                'msg' => '添加成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }   

    public function addSpecValue(Request $request){
        try {
            $data = $request->post();
            $goods_id = $data['goods_id'];
            $spec_id = $data['spec_id'];
            $spec_value = $data['spec_value'];

            if(empty($spec_value)){
                throw new Exception('规格值不能为空');
            }

            $spec = GoodsSpecModel::find($spec_id);
            if (!$spec) {
                throw new Exception('规格不存在');
            }

            $specValues = $spec->spec_value;
            $specValuesArray = array_filter(explode('@', $specValues), function($value) {
                return !empty($value);
            });

            $isEdit = $data['is_edit'];
            $selectedSpecValue = $data['selected_spec_value'];
            
            if ($isEdit) {
                // 已存在，执行编辑操作（如果需要更新其他内容可以在这里处理）
                $specValuesArray = array_filter($specValuesArray, function($value) use ($selectedSpecValue) {
                    return $value != $selectedSpecValue;
                });
                $specValuesArray[] = $spec_value;
            } else {
                // 不存在，执行新建操作
                $specValuesArray[] = $spec_value;
            }
            
            $specValues = implode('@', $specValuesArray);
            $spec->spec_value = $specValues;    

            if (!$spec->save()) {
                throw new Exception($isEdit ? '编辑规格值失败' : '添加规格值失败');
            }

            if($isEdit){

            }

            return json([
                'msg' => $isEdit ? '规格值已存在，无需重复添加' : '添加成功',
                'code' => 20000,
                'data' => [
                    'is_edit' => $isEdit
                ]
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }   

    public function delSpecValue(Request $request){
        try {
            $data = $request->post();
            $goods_id = $data['goods_id'];
            $spec_id = $data['spec_id'];
            $spec_value = $data['spec_value'];

            $spec = GoodsSpecModel::find($spec_id);
            if (!$spec) {
                throw new Exception('规格不存在');
            }

            $specValues = $spec->spec_value;
            $specValues = empty($specValues) ? [] : explode('@', $specValues);
            $specValues = array_filter($specValues, function($value) {
                return !empty($value);
            });
            $specValues = array_filter($specValues, function($value) use ($spec_value) {
                return $value != $spec_value;
            });
            $specValues = implode('@', $specValues);
            $spec->spec_value = $specValues;

            if (!$spec->save()) {
                throw new Exception('删除规格值失败');
            }

            return json([
                'msg' => '删除成功',
                'code' => 20000
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    public function ku(Request $request){
        try {
            $data = $request->post();
            $goods_id = $data['goods_id'];

            // 获取商品信息
            $goods = GoodsModel::find($goods_id);
            if (!$goods) {
                throw new Exception('商品不存在');
            }

            $kus = GoodsKuModel::where('goods_id','=',$goods_id)->get();
            foreach($kus as &$ku){
                $ku['specs'] = explode('@', $ku->specs);
                $ku['specs_data'] = json_decode($ku->specs_data, true);

                $ku['created_at'] = date('Y-m-d H:i:s', $ku->created_at);
            }

            return json([
                'data' => [
                    'kus' => $kus
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);

        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 生成SKU矩阵
     * @param array $specValuesList 规格值列表
     * @return array
     */
    private function generateSkuMatrix(array $specValuesList): array
    {
        if (empty($specValuesList)) {
            return [];
        }

        // 使用笛卡尔积生成所有可能的SKU组合
        $result = [[]];
        
        foreach ($specValuesList as $specValues) {
            $temp = [];
            foreach ($result as $existing) {
                foreach ($specValues as $value) {
                    $temp[] = array_merge($existing, [$value]);
                }
            }
            $result = $temp;
        }

        return $result;
    }

    /**
     * 保存SKU数据（新建/编辑）
     * @param Request $request
     * @return Response
     */
    public function saveKu(Request $request): Response
    {
        try {
            $data = $request->post();
            $sku_data = $data['sku_data'];

            // 获取商品信息
            $goods = GoodsModel::find($sku_data['goods_id']);
            if (!$goods) {
                throw new Exception('商品不存在');
            }

            $specs = [];
            foreach ($sku_data['specs'] as $k=>$spec) {
                $specs[] = $spec['value'];
            }
            $specsString = implode('@', $specs);

            // 判断是新建还是编辑
            $isEdit = !empty($sku_data['id']) && $sku_data['id'] != 0;

            if ($isEdit) {
                // 编辑模式
                $model = GoodsKuModel::find($sku_data['id']);
                if (!$model) {
                    throw new Exception('SKU不存在');
                }

                // 检查是否已存在相同规格的SKU（排除当前编辑的SKU）
                $existingSku = GoodsKuModel::findBySpecsFlexible($sku_data['goods_id'], $specsString);
                if ($existingSku && $existingSku->id != $sku_data['id']) {
                    throw new Exception('该规格组合的SKU已存在');
                }

                // 更新数据
                $model->name = $sku_data['name'];
                $model->price = $sku_data['price'];
                $model->v = $sku_data['v'];
                $model->specs_data = json_encode($sku_data['specs'], 256);
                $model->updated_at = time();
                $model->specs = $specsString;

                if (!$model->save()) {
                    throw new Exception('更新失败');
                }

                return json([
                    'code' => 20000,
                    'msg' => '更新成功',
                    'data' => [
                        'id' => $model->id
                    ]
                ]);
            } else {
                // 新建模式
                // 检查是否已存在相同规格的SKU
                $existingSku = GoodsKuModel::findBySpecsFlexible($sku_data['goods_id'], $specsString);
                if ($existingSku) {
                    throw new Exception('该规格组合的SKU已存在');
                }

                $model = new GoodsKuModel();
                $model->goods_id = $sku_data['goods_id'];
                $model->name = $sku_data['name'];
                $model->price = $sku_data['price'];
                $model->v = $sku_data['v'];
                $model->specs_data = json_encode($sku_data['specs'], 256);
                $model->created_at = time();
                $model->updated_at = time();
                $model->specs = $specsString;

                if (!$model->save()) {
                    throw new Exception('保存失败');
                }

                return json([
                    'code' => 20000,
                    'msg' => '添加成功',
                    'data' => [
                        'id' => $model->id
                    ]
                ]);
            }

        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    public function delKu(Request $request)
    {
        try {
            $data = $request->post();
            $model = GoodsKuModel::find($data['id']);
            if (!$model) {
                throw new Exception('SKU不存在');
            }
            if (!$model->delete()) {
                throw new Exception('删除失败');
            }
            return json([
                'data' => null,
                'msg' => '删除成功',
                'code' => 20000
            ]);
        }catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 根据规格组合获取SKU信息
     * @param Request $request
     * @return Response
     */
    public function getSkuBySpecs(Request $request): Response
    {
        try {
            $goods_id = $request->get('goods_id');
            $specs = $request->get('specs');

            if (empty($goods_id) || empty($specs)) {
                throw new Exception('参数错误');
            }

            // 获取商品信息
            $goods = GoodsModel::find($goods_id);
            if (!$goods) {
                throw new Exception('商品不存在');
            }

            // 根据规格组合查找SKU
            $sku = GoodsKuModel::findBySpecs($goods_id, $specs);
            
            if (!$sku) {
                return json([
                    'data' => null,
                    'msg' => '该规格组合不存在',
                    'code' => 0
                ]);
            }

            return json([
                'data' => [
                    'id' => $sku->id,
                    'goods_id' => $sku->goods_id,
                    'specs' => $sku->specs,
                    'price' => (float)$sku->price,
                    'stock' => (int)$sku->v,
                    'created_at' => $sku->created_at,
                    'updated_at' => $sku->updated_at
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);

        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取商品的所有SKU列表
     * @param Request $request
     * @return Response
     */
    public function getSkuList(Request $request): Response
    {
        try {
            $goods_id = $request->get('goods_id');

            if (empty($goods_id)) {
                throw new Exception('参数错误');
            }

            // 获取商品信息
            $goods = GoodsModel::find($goods_id);
            if (!$goods) {
                throw new Exception('商品不存在');
            }

            // 获取所有SKU
            $skuList = GoodsKuModel::getByGoodsId($goods_id);
            
            $data = [];
            foreach ($skuList as $sku) {
                $data[] = [
                    'id' => $sku->id,
                    'goods_id' => $sku->goods_id,
                    'specs' => $sku->specs,
                    'sku_code' => GoodsKuModel::generateSkuCode($sku->goods_id, $sku->specs),
                    'price' => (float)$sku->price,
                    'stock' => (int)$sku->v,
                    'created_at' => $sku->created_at,
                    'updated_at' => $sku->updated_at
                ];
            }

            return json([
                'data' => $data,
                'msg' => '获取成功',
                'code' => 20000
            ]);

        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 根据SKU编码获取SKU信息
     * @param Request $request
     * @return Response
     */
    public function getSkuByCode(Request $request): Response
    {
        try {
            $sku_code = $request->get('sku_code');

            if (empty($sku_code)) {
                throw new Exception('参数错误');
            }

            // 根据SKU编码查找SKU
            $sku = GoodsKuModel::findBySkuCode($sku_code);
            
            if (!$sku) {
                return json([
                    'data' => null,
                    'msg' => 'SKU不存在',
                    'code' => 0
                ]);
            }

            return json([
                'data' => [
                    'id' => $sku->id,
                    'goods_id' => $sku->goods_id,
                    'specs' => $sku->specs,
                    'sku_code' => GoodsKuModel::generateSkuCode($sku->goods_id, $sku->specs),
                    'price' => (float)$sku->price,
                    'stock' => (int)$sku->v,
                    'created_at' => $sku->created_at,
                    'updated_at' => $sku->updated_at
                ],
                'msg' => '获取成功',
                'code' => 20000
            ]);

        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取商品相册列表
     * @param Request $request
     * @return Response
     */
    public function getImages(Request $request): Response
    {
        try {
            $goods_id = $request->get('goods_id');
            
            if (empty($goods_id)) {
                throw new Exception('商品ID不能为空');
            }

            // 验证商品是否存在
            $goods = GoodsModel::find($goods_id);
            if (!$goods) {
                throw new Exception('商品不存在');
            }

            // 获取商品图片列表
            $images = GoodsImageModel::where('goods_id', $goods_id)
                ->orderBy('sort', 'asc')
                ->orderBy('id', 'desc')
                ->get();

            $data = [];
            foreach ($images as $image) {
                $data[] = [
                    'id' => $image->id,
                    'title' => $image->title,
                    'path' => $image->path,
                    'url' => Util::pathToUrl($image->path),
                    'sort' => $image->sort,
                    'goods_id' => $image->goods_id,
                    'created_at' => $image->created_at,
                    'updated_at' => $image->updated_at
                ];
            }

            return json([
                'data' => $data,
                'msg' => '获取成功',
                'code' => 20000
            ]);

        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 添加商品图片
     * @param Request $request
     * @return Response
     */
    public function addImage(Request $request): Response
    {
        try {
            $data = $request->post();
            
            if (empty($data['goods_id']) || empty($data['path'])) {
                throw new Exception('商品ID和图片路径不能为空');
            }

            // 验证商品是否存在
            $goods = GoodsModel::find($data['goods_id']);
            if (!$goods) {
                throw new Exception('商品不存在');
            }

            $image = new GoodsImageModel();
            $image->goods_id = $data['goods_id'];
            $image->path = $data['path'];
            $image->title = $data['title'] ?? '';
            $image->sort = $data['sort'] ?? 0;
            $image->created_at = time();
            $image->updated_at = time();

            if (!$image->save()) {
                throw new Exception('添加图片失败');
            }

            return json([
                'data' => [
                    'id' => $image->id,
                    'title' => $image->title,
                    'path' => $image->path,
                    'url' => Util::pathToUrl($image->path),
                    'sort' => $image->sort,
                    'goods_id' => $image->goods_id,
                    'created_at' => $image->created_at,
                    'updated_at' => $image->updated_at
                ],
                'msg' => '添加成功',
                'code' => 20000
            ]);

        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 更新商品图片信息
     * @param Request $request
     * @return Response
     */
    public function updateImage(Request $request): Response
    {
        try {
            $data = $request->post();
            
            if (empty($data['id'])) {
                throw new Exception('图片ID不能为空');
            }

            $image = GoodsImageModel::find($data['id']);
            if (!$image) {
                throw new Exception('图片不存在');
            }

            $image->title = $data['title'] ?? $image->title;
            $image->sort = $data['sort'] ?? $image->sort;
            $image->updated_at = time();

            if (!$image->save()) {
                throw new Exception('更新失败');
            }

            return json([
                'data' => [
                    'id' => $image->id,
                    'title' => $image->title,
                    'path' => $image->path,
                    'url' => Util::pathToUrl($image->path),
                    'sort' => $image->sort,
                    'goods_id' => $image->goods_id,
                    'created_at' => $image->created_at,
                    'updated_at' => $image->updated_at
                ],
                'msg' => '更新成功',
                'code' => 20000
            ]);

        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 删除商品图片
     * @param Request $request
     * @return Response
     */
    public function deleteImage(Request $request): Response
    {
        try {
            $id = $request->post('id');
            
            if (empty($id)) {
                throw new Exception('图片ID不能为空');
            }

            $image = GoodsImageModel::find($id);
            if (!$image) {
                throw new Exception('图片不存在');
            }

            if (!$image->delete()) {
                throw new Exception('删除失败');
            }

            return json([
                'data' => null,
                'msg' => '删除成功',
                'code' => 20000
            ]);

        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
}
